package org.jeecg.modules.message.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.modules.message.entity.MessageBizConfig;
import org.jeecg.modules.message.enums.MessageBizTypeEnums;
import org.jeecg.modules.message.service.IMessageBizConfigService;
import org.jeecg.modules.message.service.impl.EmailService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;

import java.text.MessageFormat;

/**
 * @author by sean
 * @desc: 租车支付处理
 * @since 2024-09-24 星期二 15:04:08
 */
@Slf4j
@RequiredArgsConstructor
@RabbitComponent(value = "message.emailListener")
public class MessageEmailHandler extends BaseRabbiMqHandler<BaseMap> {

    private final EmailService emailService;

    private final IMessageBizConfigService messageBizConfigService;

    @RabbitListener(queues = "message.email")
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                String to =  map.get("to");
                String tenantId = map.get("tenantId");
                String bizType = map.get("bizType");
                Object[] arguments = map.get("arguments");
                if(ObjectUtil.isEmpty(to)){
                    log.error("收件邮箱不能为空");
                    return;
                }
                try {
                    MessageBizTypeEnums bizTypeEnums = MessageBizTypeEnums.getEnumByValue(bizType);
                    MessageBizConfig messageBizConfig = messageBizConfigService
                            .getOne(new QueryWrapper<MessageBizConfig>().eq("biz_type", bizTypeEnums.getValue()));
                    String text = MessageFormat.format(messageBizConfig.getEmailTemplate(), arguments);
                    emailService.sendSimpleMessage(tenantId, to, bizTypeEnums.getLabel(), text);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
